<template>
  <div class="users_container">
    <div v-loading="loading" class="main" element-loading-text="加载中...">
      <div ref="headerRef" class="header">
        <div class="btn_group">
          <HPlainButton @click="addData">新增网点机构</HPlainButton>
          <el-dropdown trigger="click">
            <HButton :disabled="selecttion.length === 0">
              批量操作
              <el-icon class="el-icon--right"><arrow-down /></el-icon>
            </HButton>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item @click="changeAll(1)">
                  <el-icon>
                    <CircleCheck />
                  </el-icon>
                  批量启用
                </el-dropdown-item>
                <el-dropdown-item @click="changeAll(2)">
                  <el-icon>
                    <Warning />
                  </el-icon>
                  批量禁用
                </el-dropdown-item>
                <el-dropdown-item @click="changeAll(3)">
                  <el-icon>
                    <Delete />
                  </el-icon>
                  批量删除
                </el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </div>
        <div class="search">
          <el-input
            v-model.trim="userListSearch.name"
            placeholder="搜索"
            class="input-width userSearch"
            clearable
            @keyup.enter="getList"
            @clear="getList"
          />
          <HButton type="primary" @click="getList">
            <el-icon>
              <Search />
            </el-icon>
            搜索
          </HButton>
          <HButton @click="clearVlaue">
            <el-icon>
              <RefreshRight />
            </el-icon>
            重置
          </HButton>
        </div>
      </div>
      <div class="table" :style="tableStyle">
        <el-table
          ref="tableDom"
          border
          stripe
          resizable
          :data="userList"
          height="100%"
          @selection-change="handleChange"
        >
          <el-table-column type="selection" width="40" fixed />
          <!-- 序号 -->
          <el-table-column label="序号" width="50" type="index" :align="'center'" fixed="left" />
          <el-table-column show-overflow-tooltip prop="name" label="机构名称" width="160" />
          <el-table-column show-overflow-tooltip prop="code" label="机构编号" width="160" />
          <!-- 状态 -->
          <el-table-column prop="disabled" label="状态" width="70" fixed="right" :align="'center'">
            <template #default="scope">
              <div style="display: flex; justify-content: center">
                <HStatus v-show="!scope.row.disabled" type="primary">启用</HStatus>
                <HStatus v-show="scope.row.disabled" type="info">禁用</HStatus>
              </div>
            </template>
          </el-table-column>
          <el-table-column show-overflow-tooltip prop="gmtCreate" label="创建时间" width="128" />
          <el-table-column show-overflow-tooltip prop="gmtUpdate" label="更新时间" width="128" />
          <el-table-column fixed="right" label="操作" width="90">
            <template #default="i">
              <el-space :size="0" :spacer="spacer">
                <HLink @click="editShowFun(i.row)">编辑</HLink>
                <HLink type="error" @click="deleteNet(i.row)">删除</HLink>
              </el-space>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="pagination">
        <Pagination
          ref="paginDom"
          :list_total="total"
          @size-change="getList"
          @current-change="getList(false)"
        />
      </div>
      <h-dialog
        v-model="addDialog"
        :title="userForm.title"
        :loading="addLoading"
        :content-padding-top="24"
      >
        <el-form
          ref="userFormRef"
          :model="userForm"
          :rules="rules"
          label-position="top"
          inline-message
          class="modal_form_content add_customer_modal_form"
          @validate="handleAddCustomerFormValidate"
        >
          <el-form-item label="机构编号" prop="code">
            <el-input v-model.trim="userForm.code" placeholder="请输入" clearable />
          </el-form-item>
          <el-form-item label="机构名称" prop="name">
            <el-input v-model.trim="userForm.name" placeholder="请输入" clearable />
          </el-form-item>
          <el-form-item label="状态" class="same_line">
            <div class="switch_container">
              <el-switch v-model="userForm.disabled" />
              <span v-if="userForm.disabled">启用</span>
              <span v-else>禁用</span>
            </div>
          </el-form-item>
        </el-form>
        <template #footer>
          <h-button is-modal type="primary" @click="saveData(userFormRef)">保存</h-button>
          <h-button is-modal @click="onAddCustomerModalCancelClick"> 取消 </h-button>
        </template>
      </h-dialog>
    </div>
  </div>
</template>

<script setup lang="ts">
  import { ref, reactive, onMounted, CSSProperties, h } from 'vue'
  import { ElMessage, ElMessageBox, FormItemProp, ElDivider } from 'element-plus'
  import type { FormInstance } from 'element-plus'
  import {
    agencygetList,
    agencygetSave,
    agencygetDelete,
    agencyNetworkDisable,
  } from '@/api/network'
  import _ from 'lodash'
  import {
    Search,
    Delete,
    Warning,
    ArrowDown,
    CircleCheck,
    RefreshRight,
  } from '@element-plus/icons-vue'
  import Pagination from '../../../../../../../components/Pagination/index.vue'
  // 间距组件的间隔符
  const spacer = h(ElDivider, {
    direction: 'vertical',
    style: 'display: flex; align-items: center;',
  })
  const addDialog = ref(false)
  const loading = ref(false)
  const headerRef = ref<HTMLDivElement | null>(null)
  const tableStyle = ref<CSSProperties>({})
  const userList = ref([]) // 列表数据
  const tableDom = ref() // 列表dom

  // 分页数据
  const paginDom = ref() // 分页dom
  const total = ref(0) // 总数目
  const userListSearch = ref({
    // 公司列表搜索条件
    page: 1,
    limit: 50,
    name: '',
  })

  // 公司表单数据
  const userForm = reactive({
    code: '',
    disabled: true,
    id: '',
    name: '',
    title: '',
  })
  const editShowFun = (obj) => {
    userForm.id = obj.id
    userForm.name = obj.name
    userForm.code = obj.code
    userForm.disabled = !obj.disabled
    addDialog.value = true
    userForm.title = '编辑网点机构'
  }
  // 验证规则
  const rules = reactive({
    code: [{ required: true, message: '请输入编号', trigger: ['change', 'blur'] }],
    name: [{ required: true, message: '请输入机构名称', trigger: ['change', 'blur'] }],
  })

  const addLoading = ref(false)
  const userFormRef = ref<FormInstance>()
  //删除
  const deleteNet = (obj) => {
    tableDom.value.clearSelection()
    selecttion.value = [obj.id]
    tableDom.value.toggleRowSelection(obj, true)
    changeAll(3)
  }
  // 重置搜索
  const clearVlaue = () => {
    userListSearch.value = {
      page: 1,
      limit: 50,
      name: '',
    }
    getList()
  }

  // 获取列表数据
  const getList = async (val = true) => {
    loading.value = true
    if (val) paginDom.value.setPage()
    userListSearch.value.page = paginDom.value.current
    userListSearch.value.limit = paginDom.value.size
    const res = await agencygetList(userListSearch.value)
    userList.value = res.data.data.rows
    total.value = parseInt(res.data.data.total)
    loading.value = false
  }

  // 新增公司
  const addData = () => {
    userForm.title = '新增网点机构'
    userForm.name = ''
    userForm.code = ''
    userForm.id = ''
    userForm.disabled = true
    addDialog.value = true
  }

  // 保存数据
  const saveData = (formEl) => {
    formEl
      .validate()
      .then(async () => {
        addLoading.value = true
        await saveMethod()
        addLoading.value = false
      })
      .catch(() => {
        // 不可以删除该注释，否则会引起报错或警告
      })
  }

  // 保存的方法
  const saveMethod = async () => {
    const dataVo = _.cloneDeep(userForm)
    dataVo.disabled = !dataVo.disabled
    await agencygetSave(dataVo).then((res) => {
      if (res.data.code == 20000) {
        addDialog.value = false
        getList()
        ElMessage({
          message: res.data.message,
          type: 'success',
          plain: true,
          showClose: true,
        })
      } else {
        ElMessage({
          message: res.data.message,
          type: 'error',
          plain: true,
          showClose: true,
        })
      }
    })
  }

  // 获取表格选中的数据
  const selecttion = ref([])
  const handleChange = (val: any[]) => {
    if (val.length != 0) {
      val.forEach((item: { id: any }) => {
        if (Object.values(selecttion.value).indexOf(item.id) == -1) {
          selecttion.value.push(item.id)
        } else {
          selecttion.value = selecttion.value.filter((i) => i == item.id)
        }
      })
    } else {
      selecttion.value = []
    }
  }

  // 封装修改状态的方法
  const changeDisable = (type, name, method, arr, status, dom, getList) => {
    if (arr.length == 0) {
      ElMessage({
        message: `请选择要${type}的${name}`,
        type: 'warning',
        plain: true,
        duration: 4000,
        showClose: true,
      })
      return
    }
    ElMessageBox({
      type: type === '删除' ? 'error' : 'warning',
      title: '提示',
      message: `确定${type}选中的${name}?`,
      showCancelButton: true,
      closeOnClickModal: false,
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      autofocus: false,
      beforeClose: (action, instance, done) => {
        if (action === 'confirm') {
          instance.confirmButtonLoading = true
          instance.confirmButtonText = '加载中...'
          setTimeout(() => {
            done()
            setTimeout(() => {
              instance.confirmButtonLoading = false
            }, 0)
          }, 1000)
        } else {
          done()
        }
      },
    }).then(async () => {
      if (status != '3') {
        await method(arr, status).then((res: any) => {
          ElMessage({
            message: res.data.message,
            type: 'success',
            plain: true,
            duration: 4000,
            showClose: true,
          })
        })
      } else {
        await method(arr).then((res: any) => {
          ElMessage({
            message: res.data.message,
            type: 'success',
            plain: true,
            duration: 4000,
            showClose: true,
          })
        })
      }
      selecttion.value = []
      dom.clearSelection()
      getList()
    })
  }

  // 批量启用/禁用/删除
  const changeAll = (n) => {
    if (n == 1) {
      changeDisable(
        '启用',
        '网点机构',
        agencyNetworkDisable,
        selecttion.value,
        true,
        tableDom.value,
        getList,
      )
    }
    if (n == 2) {
      changeDisable(
        '禁用',
        '网点机构',
        agencyNetworkDisable,
        selecttion.value,
        false,
        tableDom.value,
        getList,
      )
    }
    if (n == 3) {
      changeDisable(
        '删除',
        '网点机构',
        agencygetDelete,
        selecttion.value,
        '3',
        tableDom.value,
        getList,
      )
    }
  }

  const addCustomerFormValidateResult = ref({
    name: true,
    phone: true,
    userTypeId: true,
    address: true,
    addrs: true,
  })

  const handleAddCustomerFormValidate = (prop: FormItemProp, isValid: boolean) => {
    addCustomerFormValidateResult.value[prop as string] = isValid
  }

  const onAddCustomerModalCancelClick = () => {
    addDialog.value = false
    addCustomerFormValidateResult.value = {
      name: true,
      phone: true,
      userTypeId: true,
      address: true,
      addrs: true,
    }
  }
  const setTableStyle = () => {
    const headerHeight = headerRef.value ? headerRef.value.scrollHeight : 0
    tableStyle.value.maxHeight = `calc(100% - 24px - 28px - ${headerHeight}px)`
  }
  defineExpose({ getList })
  onMounted(() => {
    getList()
    setTableStyle()
    window.addEventListener('resize', setTableStyle)
  })
</script>

<style scoped lang="scss">
  @import './index';
</style>
